package com.googlecode.perfectable.prosperable.channel;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

import com.googlecode.perfectable.prosperable.message.ClientMessage;
import com.googlecode.perfectable.prosperable.message.ServerMessage;

public class StandardMessageSerializer implements MessageSerializer {

	private ObjectMapper serverMapper = new ObjectMapper();
	private ObjectMapper clientMapper = new ObjectMapper();

	public StandardMessageSerializer(Iterable<Class<? extends ServerMessage>> registeredServerMessages,
			Iterable<Class<? extends ClientMessage>> registeredClientMessages) {
		for(Class<? extends ClientMessage> clientMessage : registeredClientMessages) {
			this.clientMapper.registerSubtypes(clientMessage);
		}
		for(Class<? extends ServerMessage> clientMessage : registeredServerMessages) {
			this.serverMapper.registerSubtypes(clientMessage);
		}
	}

	@Override
	public ClientMessage parseClientMessage(String messageData) {
		try {
			return this.clientMapper.readValue(messageData, ClientMessage.class);
		}
		catch(IOException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

	@Override
	public String serializeServerMessage(ServerMessage message) {
		try {
			return this.serverMapper.writeValueAsString(message);
		}
		catch(IOException e) {
			throw new RuntimeException(e); // TODO Auto-generated catch block
		}
	}

}
